﻿using B.S.DataBasic.Domain;
using B.S.DataBasic.Domain.GoodInfra;
using B.S.DataBasic.ErrorCode;
using B.S.DataBasic.Infrastructure;
using B.S.DataBasic.Write.API.Application;
using B.S.DataBasic.Write.API.Dtos;
using MediatR;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util; 
 


namespace B.S.DataBasic.Write.API.Controllers
{
    /// <summary>
    /// 溯源表
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TranceController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly DataDbContext db;
        public TranceController(IMediator mediator, IWebHostEnvironment webHostEnvironment, DataDbContext db)
        {
            this.mediator = mediator; 
            this._webHostEnvironment = webHostEnvironment;
            this.db = db;
        }

        /// <summary>
        /// 溯源表添加
        /// </summary>
        /// <param name="add"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<Traceabilitable>> AddTrance(AddTraceCommand add)
        {
            return await mediator.Send(add);
        }

        /// <summary>
        /// 溯源表删除
        /// </summary>
        /// <param name="add"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<Traceabilitable>> DelTrance(DelTranceCommand del)
        {
            return await mediator.Send(del);
        }

        ///// <summary>
        ///// 图片
        ///// </summary>
        ///// <param name="file"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public IActionResult Img(IFormFile file)
        //{
        //    try
        //    {
        //        //全球唯一标识符
        //        var str = Guid.NewGuid().ToString();
        //        //3.完成图片上传
        //        string p = Directory.GetCurrentDirectory() + @"\wwwroot\files\" + str + file.FileName;
        //        using (FileStream fs = new FileStream(p, FileMode.Create))
        //        {
        //            file.CopyTo(fs);
        //            fs.Flush();
        //        }
        //        return Ok("http://localhost:62301/Coverimage/" + str + file.FileName);

        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }
        //}

        ///// <summary>
        ///// 上传图片 
        ///// </summary>
        ///// <param name="file"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public IActionResult Upload(IFormFile file)
        //{
        //    if (file == null || file.Length == 0)
        //    {
        //        return BadRequest("请选择要上传的文件");
        //    }

        //    var now = DateTime.Now;
        //    string yearFolder = now.Year.ToString();
        //    string monthFolder = now.Month.ToString("D2");
        //    string dayFolder = now.Day.ToString("D2");

        //    string uploadsRoot = Path.Combine(_webHostEnvironment.WebRootPath, "uploads");
        //    string uploadPath = Path.Combine(uploadsRoot, yearFolder, monthFolder, dayFolder);

        //    if (!Directory.Exists(uploadPath))
        //    {
        //        Directory.CreateDirectory(uploadPath);
        //    }

        //    string filePath = Path.Combine(uploadPath, file.FileName);

        //    using (var stream = new FileStream(filePath, FileMode.Create))
        //    {
        //        file.CopyTo(stream);
        //    }

        //    return Ok($"文件上传成功，保存路径：{filePath}");
        //}

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("UploadImages")] // 指定该方法处理 HTTP POST 请求
        public async Task<IActionResult> UploadImages(IFormFile file) // 定义一个异步方法，接收一个文件类型的参数
        {
            if (file == null || file.Length == 0) // 检查文件是否为空或文件大小
            {
                return BadRequest("文件不能为空");
            }

            string saveKey = "Pic/" + file.FileName; // 设置上传文件保存的路径和文件名,可以随便输入 不用创建可自动生成
            string bucket = "rabit2"; // 七牛云存储空间名称   七牛云仓库名称
            Mac mac = new Mac("dLoHk-uuuJR-pT1Z1sJ5xzBxmaXemo-_06VKbACt", "zxEZc6a3bnz3EZZLcfb9xVrvrFE96ZtOKQR3K20Q"); // 替换为您七牛云账号的访问密钥和密钥

            // 设置上传策略
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = bucket + ":" + saveKey; // 设置 Scope 为具体的文件路径，即指定存储空间和保存路径

            // 创建上传凭证
            string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString()); // 生成上传凭证，凭证包含了上传策略信息

            // 配置上传管理器
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_North; // 设置上传区域，这里是华北区域   自己选的区域,这个是华北,别的自己搜一下
            config.UseHttps = true; // 使用 HTTPS 进行上传
            config.UseCdnDomains = true; // 使用 CDN 域名加速上传
            config.ChunkSize = ChunkUnit.U512K; // 设置分块上传的块大小

            // 实例化表单上传对象
            FormUploader target = new FormUploader(config);

            // 上传文件
            HttpResult result = target.UploadStream(file.OpenReadStream(), saveKey, token, null); // 调用上传方法，上传文件流，传入保存路径和上传凭证

            // 检查上传结果
            if (result.Code == 200) // 判断上传是否成功（返回状态码200表示成功）
            {
                return Ok(file.FileName); // 返回200响应，上传成功，返回文件名
            }
            else
            {
                return BadRequest("上传失败：" + result.Text); // 如果上传失败，返回400错误响应，包含错误信息
            }
        }

        /// <summary>
        /// 保健表查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Imunitys>>> GetHealthInfos()
        {
            return await db.Imunitys.ToListAsync();
        }
        /// <summary>
        /// 保健表添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<Imunitys>> AddHealthInfo(Imunitys healthInfo)
        {
            db.Imunitys.Add(healthInfo);
            await db.SaveChangesAsync();
            return CreatedAtAction(nameof(GetHealthInfos), new { id = healthInfo.ImunityId }, healthInfo);
        }
        /// <summary>
        /// 保健表删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteHealthInfo(int id)
        {
            var healthInfo = await db.Imunitys.FindAsync(id);
            if (healthInfo == null)
            {
                return NotFound();
            }

            db.Imunitys.Remove(healthInfo);
            await db.SaveChangesAsync();
            return NoContent();
        }

        
    }
}
